package javablackbelt.main;

import java.sql.Connection;
import java.util.List;
import java.util.Locale;

import javablackbelt.dao.UserDao;
import javablackbelt.domain.User;
import javablackbelt.i18n.LocaleHolder;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainPersistenceTest {

	protected final static Logger logger = Logger.getLogger(MainPersistenceTest.class);

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		LocaleHolder.setUserLocale(new Locale("es"));
		
		ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
									"classpath:/javablackbelt/config/applicationContext.xml",
									"classpath:/javablackbelt/config/application-db.xml",
									"classpath:/javablackbelt/config/application-messageSource.xml"});
		
		((ConfigurableApplicationContext)appContext).registerShutdownHook();

		DataSource dataSource = (DataSource)appContext.getBean("dataSource");
		Connection connection = dataSource.getConnection();
		
		if (connection != null) {
			logger.info("Connected to " + connection.getMetaData().getDatabaseProductName());
		}
		
		UserDao userDao = (UserDao) appContext.getBean("userDao");
		
		// Remove all users
		logger.info("Removing all users...");
		userDao.deleteAll();
		displayAllUsers(userDao);
		
		logger.info("Inserting 2 new users...");
		// Insert 2 new users
		User user = new User();
		user.setFirstName("Albert");
		user.setLastName("Einstein");
		userDao.save(user);

		user = new User();
		user.setFirstName("Nicola");
		user.setLastName("Tesla");
		userDao.save(user);
		
		displayAllUsers(userDao);
		
		logger.info("Updating 1 user...");
		user.setLastName("Paganini");
		userDao.save(user);
		
		displayAllUsers(userDao);
		
		logger.info("Looking for all user with a 'g' in their last name...");
		List<User> foundUsers = userDao.findByFirstLetterOfLastName('g');
		displayUserList(foundUsers);
		
		logger.info("Deleting user with id = " + user.getId());
		userDao.delete(user);
		displayAllUsers(userDao);
		
		logger.info("Deleting all users...");
		userDao.deleteAll();
		displayAllUsers(userDao);
	}

	private static void displayAllUsers(UserDao userDAO) {
		List<User> allUsers = userDAO.getAll();
		displayUserList(allUsers);
	}
	
	private static void displayUserList(List<User> users) {
		if (users != null) {
			
			logger.info("Number of users : " + users.size());
			
			for (User user : users) {
				logger.info(user.toString());
			}
		}
		
	}

}
